﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization
Imports Microsoft.VisualBasic


Partial Class Interfaz_frmAdminFacturaEmitir
    Inherits System.Web.UI.Page
    Dim CL As New Logica.ModuloAdministracion.ControladorLogica
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet
    Dim DataFactura As New DataSetFactura

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CL = Logica.ModuloAdministracion.ControladorLogica.getInstance

        If CL.visibilidadesFormsInternos("Administracion", Session("user").ToString) = False Then
            Response.Redirect("Index.aspx")
        End If

        cargarValoresIniciales()

        'se guardan datos en secion para el positback de la pagina respecto al los datos del datagridview
        If Session("EmiteFactura") Is Nothing Then
            Session("EmiteFactura") = dtDatos
        Else
            dtDatos = DirectCast(Session("EmiteFactura"), DataTable)

        End If

        If Not Page.IsPostBack Then
            Try
                dtDatos.Columns.Add(New DataColumn("ITEM"))
                dtDatos.Columns.Add(New DataColumn("CODIGO"))
                dtDatos.Columns.Add(New DataColumn("DETALLE"))
                dtDatos.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatos.Columns.Add(New DataColumn("PRECIOUNITARIO"))

                Me.GridFacturaEmitida.DataBind()
                Me.GridFacturaEmitida.DataSource = Me.dtDatos
            Catch
            End Try
        End If

        'Me.GridFacturaEmitida.DataBind()
        Me.GridFacturaEmitida.DataSource = Me.dtDatos
    End Sub

#Region "Funcionalidades"
   
    Private Sub IngresarItem()
        Try
            Dim drDatos As DataRow = dtDatos.NewRow

            If Me.txtCodigoEF.Text <> "" And Me.txtDetalleEF.Text <> _
            "" And Me.TxtCantidadEF.Text <> "" And Me.TxtPrecioUnitarioEF.Text <> "" Then

                drDatos.Item("ITEM") = Me.DropItemEF.Text
                drDatos.Item("CODIGO") = Me.txtCodigoEF.Text
                drDatos.Item("DETALLE") = Me.txtDetalleEF.Text
                drDatos.Item("CANTIDAD") = Me.TxtCantidadEF.Text
                drDatos.Item("PRECIOUNITARIO") = CInt(Me.TxtPrecioUnitarioEF.Text)

                dtDatos.Rows.Add(drDatos)

                Me.GridFacturaEmitida.DataSource = dtDatos
                Me.GridFacturaEmitida.DataBind()

                Me.LimpiarItemFacturaEmitida()
                Me.GridFacturaEmitida.ForeColor = Drawing.Color.Blue
                Me.LabelAvisoEF.Text = "Los datos han sido ingresados satisfactoriamente"
            Else
                Me.LabelAvisoEF.ForeColor = Drawing.Color.Red
                Me.LabelAvisoEF.Text = "Complete todos los datos"
            End If

        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Private Sub cargarValoresIniciales()
        Dim ArrayItem As New ArrayList
        Dim ArrayOrdenCompra As New ArrayList
        Dim ArrayGuiaDespacho As New ArrayList
        Dim ArrayCliente As New ArrayList
        Dim arrayVendedores As New ArrayList
        Dim i As Integer

        ArrayItem = CL.ObtenerMaterial()
        ArrayOrdenCompra = CL.ObtenerOrdenCompra()
        ArrayGuiaDespacho = CL.obtenerGuiaDespacho()
        ArrayCliente = CL.obtenerCliente()
        arrayVendedores = CL.obtenerEmpleado()


        If Not Page.IsPostBack Then

            Dim itemIva As New ListItem
            itemIva.Text = "0.17"
            itemIva.Value = "0.17"
            Me.DropIva.Items.Add(itemIva)
            Dim itemIva1 As New ListItem
            itemIva1.Text = "0.18"
            itemIva1.Value = "0.18"
            Me.DropIva.Items.Add(itemIva1)
            Dim itemIva2 As New ListItem
            itemIva2.Text = "0.19"
            itemIva2.Value = "0.19"
            Me.DropIva.Items.Add(itemIva2)
            Dim itemIva3 As New ListItem
            itemIva3.Text = "0.20"
            itemIva3.Value = "0.20"
            Me.DropIva.Items.Add(itemIva3)
            Dim itemIva4 As New ListItem
            itemIva4.Text = "0.21"
            itemIva4.Value = "0.21"
            Me.DropIva.Items.Add(itemIva4)


            For i = 0 To arrayVendedores.Count - 1
                Dim itemVendedor As New ListItem
                Dim vendedor As Empleado = DirectCast(arrayVendedores.Item(i), Empleado)
                itemVendedor.Text = vendedor.Nombre + " " + vendedor.Apellido
                itemVendedor.Value = vendedor.Rut

                Me.DropVendedor.Items.Add(itemVendedor)
            Next

            For i = 0 To ArrayItem.Count - 1
                Dim itemEF As New ListItem
                Dim material As Material = DirectCast(ArrayItem.Item(i), Material)
                itemEF.Text = material.Nombre
                itemEF.Value = material.ID

                Me.DropItemEF.Items.Add(itemEF)
            Next

            For i = 0 To ArrayOrdenCompra.Count - 1
                Dim OrdenCompraEF As New ListItem
                Dim OrdenCompra As OrdenCompra = DirectCast(ArrayOrdenCompra.Item(i), OrdenCompra)
                OrdenCompraEF.Text = OrdenCompra.NumeroDeOrden
                OrdenCompraEF.Value = OrdenCompra.NumeroDeOrden

                Me.DropOrdenCompraEF.Items.Add(OrdenCompraEF)
            Next

            For i = 0 To ArrayGuiaDespacho.Count - 1
                Dim guiaDespachoEF As New ListItem
                Dim guiaDespacho As GuiaDespacho = DirectCast(ArrayGuiaDespacho.Item(i), GuiaDespacho)
                guiaDespachoEF.Text = guiaDespacho.Id
                guiaDespachoEF.Value = guiaDespacho.Id

                Me.DropGuiaDespachoEF.Items.Add(guiaDespachoEF)
            Next

            For i = 0 To ArrayCliente.Count - 1
                Dim itemcliente As New ListItem
                Dim cliente As Cliente = DirectCast(ArrayCliente.Item(i), Cliente)
                itemcliente.Value = cliente.Rut
                itemcliente.Text = cliente.RznSocial

                Me.DropCliente.Items.Add(itemcliente)
            Next

            Me.DropIva.SelectedValue = "0.19"
        End If
    End Sub

    Private Sub IngresaFacturaBD()
        Dim filaGrid As GridViewRow

        'Datos Fijos
        Dim cliente As Cliente = DirectCast(CL.obtenerCliente(DropCliente.SelectedValue).Item(0), Cliente)
        Dim Fecha As String = Me.TxtFecha.Text
        Dim dia As String = Fecha.Substring(0, 2)
        Dim mes As String = Fecha.Substring(3, 2)
        Dim año As String = Fecha.Substring(6, 4)
        Dim iva As Integer = 0
        Dim TotalNeto As Integer = 0
        Dim TotalBruto As Integer = 0
        Dim TotalPorItem As Integer = 0
        Dim rznSocial As String = ""
        Dim direccion As String = ""
        Dim giro As String = ""
        Dim rut As String = ""
        Dim comuna As String = ""
        Dim telefono As String = ""
        Dim guiaDespacho As String = ""
        Dim vendedor As String = ""
        Dim ordenCompra As String = ""
        Dim condVenta As String = ""
        'Detalle de items
        Dim factItem As String = ""
        Dim facCodigo As String = ""
        Dim factDetalle As String = ""
        Dim factCantidad As String = ""
        Dim factPrecioUnitario As String = ""
        'Declaraciones para insert a BD
        Dim ArrayItemFactura As New ArrayList

        Try

            'Carga De Datos del Destinatario
            rznSocial = cliente.RznSocial
            direccion = cliente.Direccion
            giro = cliente.Giro
            rut = cliente.Rut
            comuna = cliente.Comuna
            telefono = cliente.Telefono
            guiaDespacho = DropGuiaDespachoEF.Text
            vendedor = Me.DropVendedor.Text
            ordenCompra = DropOrdenCompraEF.Text
            condVenta = TxtCondVentaEF.Text

            'Suma Valores de actividades
            With Me.GridFacturaEmitida
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridFacturaEmitida.Rows(fila)

                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    factItem = filaGrid.Cells(1).Text
                    facCodigo = filaGrid.Cells(2).Text
                    factDetalle = filaGrid.Cells(3).Text
                    factCantidad = filaGrid.Cells(4).Text
                    factPrecioUnitario = filaGrid.Cells(5).Text

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem

                    Dim itemFactura As New Item(filaGrid.Cells(2).Text, filaGrid.Cells(3).Text, filaGrid.Cells(4).Text, filaGrid.Cells(5).Text, _
                                                filaGrid.Cells(1).Text, CInt(filaGrid.Cells(5).Text) * 0.19, filaGrid.Cells(5).Text)
                    ArrayItemFactura.Add(itemFactura)
                Next fila
            End With


            'Calculo Valores Neto - Bruto - Iva
            Dim ivaDrop As Double = Me.DropIva.SelectedValue

            iva = TotalNeto * ivaDrop
            TotalBruto = TotalNeto + iva

            'Creacion factura e Ingreso a la BD
            Dim nuevaFactura As New FacturaEmitida()
            nuevaFactura.ArrayItem = ArrayItemFactura
            nuevaFactura.CondVenta = TxtCondVentaEF.Text
            nuevaFactura.Fecha = Fecha
            nuevaFactura.ID = ""
            nuevaFactura.Iva = iva
            nuevaFactura.Neto = TotalNeto
            nuevaFactura.RefCliente = cliente
            nuevaFactura.Total = TotalBruto
            CL.InsertarFactura(nuevaFactura)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try

    End Sub

    Private Sub llenaDatosCliente()

        Dim Arraycliente As ArrayList = CL.obtenerClienteGeneral(DropCliente.SelectedValue)

        txtFono.Text = DirectCast(Arraycliente.Item(0), Cliente).Telefono
        txtDireccion.Text = DirectCast(Arraycliente.Item(0), Cliente).Direccion
        txtrut.Text = DirectCast(Arraycliente.Item(0), Cliente).Rut
        txtGiro.Text = DirectCast(Arraycliente.Item(0), Cliente).Giro
        txtComuna.Text = DirectCast(Arraycliente.Item(0), Cliente).Comuna
        txtCiudad.Text = DirectCast(Arraycliente.Item(0), Cliente).Ciudad
    End Sub

#End Region

#Region "Reportes"
    Function CargarFactura() As Boolean
        Dim nfi As NumberFormatInfo = New CultureInfo("en-US", False).NumberFormat
        nfi.CurrencyDecimalDigits = 0
        nfi.CurrencyGroupSeparator = "."

        Dim myRow As DataRow = Me.DataFactura.DatosCabezera.NewRow
        Dim filaGrid As GridViewRow
        Dim myFila As DataRow

        'Datos Fijos
        Dim cliente As Cliente = DirectCast(CL.obtenerClienteGeneral(DropCliente.SelectedValue).Item(0), Cliente)
        Dim Fecha As String = "12/12/2012"
        Dim dia As String = Fecha.Substring(0, 2)
        Dim mes As String = Fecha.Substring(3, 2)
        Dim año As String = Fecha.Substring(6, 4)
        Dim iva As Integer = 0
        Dim TotalNeto As Integer = 0
        Dim TotalBruto As Integer = 0
        Dim TotalPorItem As Integer = 0

        'Declaraciones para insert a BD
        Dim ArrayItemFactura As New ArrayList

        Try
            ' Carga De Datos del Destinatario
            myRow.Item("nombre") = cliente.RznSocial
            myRow.Item("direccion") = cliente.Direccion
            myRow.Item("giro") = cliente.Giro
            myRow.Item("rut") = cliente.Rut
            myRow.Item("comuna") = cliente.Comuna
            myRow.Item("telefono") = cliente.Telefono
            myRow.Item("guiadespacho") = DropGuiaDespachoEF.Text
            myRow.Item("vendedor") = Me.DropVendedor.Text
            myRow.Item("ordencompra") = DropOrdenCompraEF.Text
            myRow.Item("condventa") = TxtCondVentaEF.Text
            myRow.Item("dia") = dia
            myRow.Item("mes") = mes
            myRow.Item("año") = año

            'Suma Valores de actividades
            With Me.GridFacturaEmitida
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridFacturaEmitida.Rows(fila)
                    myFila = DataFactura.DatosItem.NewRow

                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    myFila.Item("factItem") = filaGrid.Cells(1).Text
                    myFila.Item("facCodigo") = filaGrid.Cells(2).Text
                    myFila.Item("factDetalle") = filaGrid.Cells(3).Text
                    myFila.Item("factCantidad") = filaGrid.Cells(4).Text
                    myFila.Item("factPrecioUnitario") = filaGrid.Cells(5).Text

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem
                    DataFactura.DatosItem.Rows.Add(myFila)
                    Dim itemFactura As New Item(filaGrid.Cells(2).Text, filaGrid.Cells(3).Text, filaGrid.Cells(4).Text, filaGrid.Cells(5).Text, _
                                                filaGrid.Cells(1).Text, CInt(filaGrid.Cells(5).Text) * 0.19, filaGrid.Cells(5).Text)
                    ArrayItemFactura.Add(itemFactura)
                Next fila
            End With

            DataFactura.DatosCabezera.Rows.Add(myRow)

            'Calculo Valores Neto - Bruto - Iva
            iva = TotalNeto * 0.19
            TotalBruto = TotalNeto + iva

            myRow.Item("neto") = TotalNeto
            myRow.Item("iva") = iva
            myRow.Item("total") = TotalBruto

            'Creacion factura e Ingreso a la BD
            Dim nuevaFactura As New FacturaEmitida()
            nuevaFactura.ArrayItem = ArrayItemFactura
            nuevaFactura.CondVenta = TxtCondVentaEF.Text
            nuevaFactura.Fecha = Fecha
            nuevaFactura.ID = ""
            nuevaFactura.Iva = iva
            nuevaFactura.Neto = TotalNeto
            nuevaFactura.RefCliente = cliente
            nuevaFactura.Total = TotalBruto

            'CL.InsertarFactura(nuevaFactura)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
            Return False
        End Try
    End Function

    Public Sub GuardarReporte(ByVal repo As ReportDocument)

        Dim fileName As String = Server.MapPath("~\Interfaz\Reportes\ReporteFactura.rpt")
        repo.Load(fileName)
        repo.SetDataSource(Me.DataFactura)

        Dim info As CrystalDecisions.CrystalReports.Engine.ReportDocument = repo
        info.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.Portrait
        info.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperLetter
        Dim rptStream As New System.IO.MemoryStream
        rptStream = CType(info.ExportToStream(CrystalDecisions.[Shared].ExportFormatType.PortableDocFormat), System.IO.MemoryStream)
        Response.Clear()
        Response.ClearContent()
        Response.ClearHeaders()
        Response.Buffer = False
        Response.ContentType = "application/vnd.pdf"
        Response.AddHeader("Content-Disposition", "attachment;filename=Presupuesto-" + "0" + ".pdf")
        Response.Flush()
        Response.BinaryWrite(rptStream.ToArray())
        Response.End()

    End Sub

#End Region

#Region "Utilidades"
    Private Sub LimpiarDataGrid()
        dtDatos = DirectCast(Session("EmiteFactura"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("EmiteFactura") = dtDatos
        End If
    End Sub

    Private Sub LimpiarTodoFacturaEmitida()
        LimpiarItemFacturaEmitida()
        txtrut.Text = String.Empty
        txtDireccion.Text = String.Empty
        txtrut.Text = String.Empty
        txtFono.Text = String.Empty
        txtGiro.Text = String.Empty
        txtComuna.Text = String.Empty
        txtCiudad.Text = String.Empty

        Me.GridFacturaEmitida.DataSource = Nothing
        Me.GridFacturaEmitida.DataBind()
    End Sub

    Private Sub LimpiarItemFacturaEmitida()
        txtCodigoEF.Text = String.Empty
        txtDetalleEF.Text = String.Empty
        TxtCantidadEF.Text = String.Empty
        TxtPrecioUnitarioEF.Text = String.Empty
        TxtCondVentaEF.Text = String.Empty
    End Sub

    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub

    Private Sub vaciaGrid()
        dtDatos = DirectCast(Session("EmiteFactura"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("EmiteFactura") = dtDatos
        End If
    End Sub

#End Region

#Region "Eventos Grid"
    'Grid Material
    Protected Sub GridFacturaEmitida_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridFacturaEmitida.PageIndex = e.NewPageIndex
        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Protected Sub GridFacturaEmitida_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        'Set the edit index.
        GridFacturaEmitida.EditIndex = e.NewEditIndex
        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Protected Sub GridFacturaEmitida_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        'Reset the edit index.
        GridFacturaEmitida.EditIndex = -1
        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Protected Sub GridFacturaEmitida_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        'Retrieve the table from the session object.
        Dim dt As DataTable = CType(Session("EmiteFactura"), DataTable)

        'Update the values.
        Dim row As GridViewRow = GridFacturaEmitida.Rows(e.RowIndex)
        'Dim actividad As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text.ToString
        Dim CODIGO As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text
        Dim DETALLE As String = (CType((row.Cells(3).Controls(0)), TextBox)).Text
        Dim CANTIDAD As String = (CType((row.Cells(4).Controls(0)), TextBox)).Text
        Dim PRECIOUNITARIO As String = (CType((row.Cells(5).Controls(0)), TextBox)).Text

        'dt.Rows(row.DataItemIndex)("ITEM") = cantidad
        dt.Rows(row.DataItemIndex)("CODIGO") = CODIGO
        dt.Rows(row.DataItemIndex)("DETALLE") = DETALLE
        dt.Rows(row.DataItemIndex)("CANTIDAD") = CANTIDAD
        dt.Rows(row.DataItemIndex)("PRECIOUNITARIO") = PRECIOUNITARIO

        'Reset the edit index.
        GridFacturaEmitida.EditIndex = -1

        'Bind data to the GridView control.
        GridFacturaEmitida.DataSource = Session("EmiteFactura")
        GridFacturaEmitida.DataBind()
    End Sub

    Sub GridFacturaEmitida_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim dt As DataTable = CType(Session("EmiteFactura"), DataTable)
        dt.Rows(e.RowIndex).Delete()
        GridFacturaEmitida.DataSource = dt
        GridFacturaEmitida.DataBind()
    End Sub
#End Region

#Region "Eventos"
    Protected Sub DropCliente_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropCliente.SelectedIndexChanged
        llenaDatosCliente()
    End Sub
#End Region

#Region "Botones"

    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        LimpiarTodoFacturaEmitida()
    End Sub

    Protected Sub Visualizador_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Visualizador.Click
        Dim repo As New ReportDocument
        Me.CargarFactura()
        GuardarReporte(repo)
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        IngresarItem()
    End Sub

    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
        IngresaFacturaBD()
        MsgBox("La factura a sido ingresada Exitosamente")
        LimpiarTodoFacturaEmitida()
        Me.vaciaGrid()
    End Sub
#End Region
End Class
